package cn.com.bluemoon.daps.standard.controller.api;

import cn.com.bluemoon.daps.common.constant.ServiceNameConstants.DapsApiStandard;
import cn.com.bluemoon.daps.common.datascope.IgnorePermission;
import cn.com.bluemoon.daps.common.domain.PageVo;
import cn.com.bluemoon.daps.common.domain.ResultBean;
import cn.com.bluemoon.daps.standard.api.RemoteStandardBasicService;
import cn.com.bluemoon.daps.standard.controller.DapStandardBasicController;
import cn.com.bluemoon.daps.standard.entity.DapStandardBasic;
import cn.com.bluemoon.daps.standard.entity.DapStandardIndex;
import cn.com.bluemoon.daps.standard.service.DapStandardBasicService;
import cn.com.bluemoon.daps.standard.service.DapStandardIndexService;
import cn.com.bluemoon.daps.standard.vo.BasicStandardAndDicVo;
import cn.com.bluemoon.daps.standard.vo.BasicStandardFormVo;
import cn.com.bluemoon.daps.standard.vo.IndexStandardVo;
import cn.com.bluemoon.daps.standard.vo.StandardInfoVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 服务接口生产类-内部调用
 *
 * @author Jarod.Kong
 */
@Api(tags = {"FeignClient服务-标准服务注入Api"})
@RestController
@RequestMapping(DapsApiStandard.API_BASIC_STD)
@IgnorePermission(name = "服务注册-标准基础服务")
public class DapsStandardBasicApi implements RemoteStandardBasicService {
    @Resource
    private DapStandardBasicService standardBasicService;

    /**
     * 基于当前服务控制器业务逻辑增加服务api
     */
    @Resource
    private DapStandardBasicController standardBasicController;

    @Resource
    private DapStandardIndexService indexService;

    @GetMapping("/getBasic/{id}")
    public ResultBean<DapStandardBasic> getBasic(@PathVariable("id") String id) {
        return ResultBean.ok(standardBasicService.getById(id));
    }

    @PostMapping("/list")
    @ApiOperation(value = "根据主题id和层级分类获取分类列表数据-用于分类列表中")
    @ApiResponses(value = {@ApiResponse(code = 200, message = "ok", response = ResultBean.class)})
    public ResultBean getPublishBasicStd(@RequestBody @Valid BasicStandardFormVo<?> formVo) {
        //由于api-dto不应该是用实体类的（具有mp特质）故自定义入口类，再转换为原有实体类
        BasicStandardFormVo<DapStandardBasic> vo = new BasicStandardFormVo<>();
        BeanUtils.copyProperties(formVo, vo);
        return standardBasicController.queryBasic(vo);
    }

    @Override
    public ResultBean<PageVo<StandardInfoVo>> pageBasicStd(String keyword, Integer pageNo, Integer pageSize) {
        IPage<DapStandardBasic> stds = standardBasicService.page(new Page<>(pageNo, pageSize), standardBasicService.bmLambdaQuery()
                .eq(DapStandardBasic::getPublishNewest, 1)
                .like(StringUtils.isNotBlank(keyword), DapStandardBasic::getName, keyword)
                .orderByDesc(DapStandardBasic::getPublishTime));
        IPage<StandardInfoVo> res = stds.convert(d -> {
            BasicStandardAndDicVo vo = new BasicStandardAndDicVo(d);
            standardBasicService.transferDicInfo(d, vo);
            return vo;
        }).convert(d -> {
            String path = Stream.of(d.getTopicName(), d.getFirstCategoryName(), d.getSecondCategoryName(), d.getThirdCategoryName()).filter(StringUtils::isNotBlank).collect(Collectors.joining("/"));
            return new StandardInfoVo(d.getId(), d.getName(), d.getEngName(), null, path, 0);
        });
        return ResultBean.ok(res)
                .convert(toPageVo());
    }

    @Override
    public ResultBean<PageVo<StandardInfoVo>> pageIndexStd(String keyword, Integer pageNo, Integer pageSize) {
        IPage<DapStandardIndex> stds = indexService.page(new Page<>(pageNo, pageSize), indexService.bmLambdaQuery()
                .eq(DapStandardIndex::getPublishNewest, 1)
                .like(StringUtils.isNotBlank(keyword), DapStandardIndex::getIndexChinName, keyword)
                .orderByDesc(DapStandardIndex::getPublishTime));
        IPage<StandardInfoVo> res = stds
                .convert(d -> {
                    IndexStandardVo vo = new IndexStandardVo(d);
                    indexService.transferDicInfo(d, vo);
                    return vo;
                }).convert(d -> {
                    String path = Stream.of(d.getTopicName(), d.getFirstCategoryName(), d.getSecondCategoryName(), d.getThirdCategoryName()).filter(StringUtils::isNotBlank).collect(Collectors.joining("/"));
                    return new StandardInfoVo(d.getId(), d.getIndexChinName(), d.getIndexEngName(), d.getDataSourceSystemName(), path, 1);
                });
        return ResultBean.ok(res)
                .convert(toPageVo());
    }

    private Function<IPage<StandardInfoVo>, PageVo<StandardInfoVo>> toPageVo() {
        return s -> {
            PageVo<StandardInfoVo> vo = new PageVo<>();
            vo.setContent(s.getRecords());
            vo.setCurrent(s.getCurrent());
            vo.setSize(s.getSize());
            vo.setTotal(s.getTotal());
            return vo;
        };
    }
}
